package main

import (
	"fmt"
	"github.com/streadway/amqp"
	"log"
)

func failOnError(err error, msg string) {
	if err != nil {
		log.Fatalf("%s,%s", msg, err)
		panic(fmt.Sprintf("%s,%s", msg, err))
	}
}

//接收消息的程序会先于发送者运行，因此在这里我们先定义一个queue，
//确保后面发送者连接到这个queue时，当前接收消息程序以运行。
func main() {
	//接着，与生产者一样，打开连接并创建通道，
	//注意这里的参数必须与send中的queue name相一致，
	//这样才能实现发送/接受的配对。
	conn, err := amqp.Dial("amqp://guest:guest@localhost:5672")
	failOnError(err, "Failed to connect to server")
	defer conn.Close()

	ch, err := conn.Channel()
	failOnError(err, "Failed to connect to channel")
	defer ch.Close()

	q, err := ch.QueueDeclare(
		"hello", //name
		false,   //durable
		false,   //delete when usused
		false,   // exclusive
		false,   //no-wait
		nil,     // arguments
	)

	failOnError(err, "Failed to declare a queue")

	msgs, err := ch.Consume(
		q.Name,
		"",
		true,
		false,
		false,
		false,
		nil,
	)
	failOnError(err, "Failed to register a consumer")
	forever := make(chan bool)

	go func() {
		for d := range msgs {
			log.Printf("Received a message : %s", d.Body)
		}
	}()

	log.Printf(" [*] Waiting for messages, To exit press CTRL+C")
	<-forever
}
